<?php
/**
 * File: UserController.class.php
 * Author: camy <375766145@qq.com>
 * Time: 2018/3/19 17:56
 */

namespace Home\Controller;

use Common\Service\ProjectPoints;
use Common\Service\User;

/**
 * 用户管理
 * @package Home\Controller
 */
class UserController extends BaseController
{
    /**
     * 用户个人中心
     * @desc page-get
     * @return string user.name 用户名称
     * @return string user.avatar 用户头像
     * @return string user.mobile 用户手机
     * @return string user.email 用户邮箱
     * @return string user.department 用户部门
     * @return string user.position 用户职位
     * @return float point.balance 积分余额
     * @return float point.freeze 冻结积分
     * @return float point.total 历史总积分
     */
    public function index()
    {
        $this->title = '个人中心';
        $service = User::instance();
        $data = $service->getPersonalInfo();
        $this->assign('data', $data);
        $this->render();
    }

    /**
     * 积分明细
     * @desc page-get
     * @param int $type 页面类型|yes|0-领取积分,1-积分明细
     * @return int list[].id 分配记录id
     * @return string list[].points 分配分数
     * @return int list[].status 分配状态:0-待确认（显示按钮），1-已确认,2-已申述
     * @return int list[].refuse_reason 申述原因
     * @return string list[].user_name 分配人名称
     * @return string list[].project_name 项目名称
     * @return string list[].created_at 时间
     * @request /user/pointslist
     */
    public function pointsList($type)
    {
        if ($type == 1) {
            $this->title = '积分明细';
        } else {
            $this->title = '领取积分';
        }

        if (!in_array($type, [0, 1])) {
            $this->fail('页面错误');
        }
        $service = User::instance();
        $data = $service->getUserPointsList(intval($type));
        $this->assign('data', $data);
        $this->render();
    }

    /**
     * 获取用户列表
     * @desc ajax get
     * @param string $search 搜索参数|no|姓名、手机
     * @param int $department_id 部门id|no|
     * @param int $not_project_id 项目id|no|返回不在此项目中的用户
     * @return string [].name 用户名称
     * @return string [].avatar 用户头像
     * @return string [].mobile 用户手机
     * @return string [].email 用户邮箱
     * @return string [].department 用户部门
     * @return string [].position 用户职位
     * @request /user/getlist
     */
    public function getList($search = '', $department_id = 0, $not_project_id = 0)
    {
        $service = User::instance();
        $list = $service->getUserList(strval($search), intval($department_id), intval($not_project_id));
        return $this->jsonSuccess($list);
    }

    /**
     * 确认积分分配
     * @desc ajax-post
     * @param int $id 分配记录id|yes
     * @param int $type 确认结果|yes|1-确认，2-申诉
     * @param string $reason 申诉原因|no|申诉时需要填写
     * @return int id 返回id
     * @request /user/confirmPoints
     */
    public function confirmPoints()
    {
        $post = $_POST;
        $service = ProjectPoints::instance();
        if ($post['type'] == 1) {
            $res = $service->confirmPoints(intval($post['id']));
        } else {
            if (empty($post['reason'])) {
                return $this->jsonFail('申述原因必填');
            }
            $res = $service->refusePoints(intval($post['id']), $post['reason']);
        }
        if (!$res) {
            return $this->jsonFail($service->error);
        }
        //通知分配人
        notification('project', 'confirmPoints', $post);
        return $this->jsonSuccess(['id' => $post['id']]);

    }

    /**
     * 设置用户签名
     * @desc ajax-post
     * @param string $data base64数据|yes
     * @return string path 转存的图片路径
     * @request /user/setSignature
     */
    public function setSignature()
    {
        $post = $_POST;
        $path = UPLOAD_PATH . 'Signature/';
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $post['data'], $match)) {

            $dirName = $path;
            if (!file_exists($dirName)) {
                //检查是否有该文件夹，如果没有就创建
                mkdir($dirName);
            }
            $ext = $match[2];//后缀
            $fileName = generate_random_filename('SIGN');
            $filePath = $dirName . $fileName . '.' . $ext;
            if (file_put_contents($filePath, base64_decode(str_replace($match[1], '', $post['data'])))) {
                $filePath = '/' . $filePath;
                $res = M('user')->where(['id' => user()->id])->save(['signature' => $filePath]);
                if (!$res) {
                    return $this->jsonFail('服务器忙~请稍后重试');
                }
                return $this->jsonSuccess(['path' => $filePath]);
            } else {
                return $this->jsonFail();
            }
        } else {
            return $this->jsonFail('格式错误');
        }
    }

    /**
     * 用户重置密码
     * @desc ajax-post
     * @param string $password 密码|yes|格式：4到16位（字母，数字，下划线，减号）
     * @request /user/setPassword
     */
    public function setPassword()
    {
        $password = $_POST['password'];
        //验证格式
        if (!preg_match('/^[a-zA-Z0-9_-]{4,16}$/', $password)) {
            return $this->jsonFail('密码格式错误');
        }
        $userId = user()->id;
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $res = M('user')->where(['id' => $userId])->save(['password' => $hash]);
        if (!$res) {
            return $this->jsonFail();
        }
        notification('user', 'setPassword', ['user_id' => $userId]);
        return $this->jsonSuccess();
    }


}